//
//  PageContentView.swift
//  DouYuZB
//
//  Created by 中创 on 2020/4/21.
//  Copyright © 2020 梁森. All rights reserved.
//

import UIKit

protocol PageContentViewDelegate:class {
    func pageContentView(contentView:PageContentView, progress:CGFloat, sourceIndex:Int, targetIndex:Int)
}

let cellID = "cellId"

class PageContentView: UIView {

    weak var delegate:PageContentViewDelegate?
    private var childVCs:[UIViewController]
    private weak var parentVC:UIViewController?  // weak用于解决循环引用
    var starOffsetX:CGFloat = 0
    private var isForbidScrollDelegate:Bool = false // 是否禁止滚动协议(点击titleView的时候不必再回调Scroll的回调方法)
    
    init(frame: CGRect, childVCs:[UIViewController], parentVC:UIViewController?) {
        // 没有初始化的属性放在super.init之前
        self.childVCs = childVCs
        self.parentVC = parentVC
        super.init(frame: frame)
        setupSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 懒加载
    lazy var collectionView:UICollectionView = { [weak self] in
        let collectionViewLayout = UICollectionViewFlowLayout()
        collectionViewLayout.itemSize = (self?.bounds.size)!
        collectionViewLayout.minimumLineSpacing = 0
        collectionViewLayout.minimumInteritemSpacing = 0
        collectionViewLayout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: self!.bounds, collectionViewLayout: collectionViewLayout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.delegate = (self!);
        collectionView.dataSource = (self!);
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
        return collectionView
    }()
}
// MARK: 遵守协议
extension PageContentView:UICollectionViewDelegate, UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.childVCs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
        let childVC = childVCs[indexPath.item]
        childVC.view.frame = cell.bounds
        // 为了防止重复添加
        for view in cell.subviews{
            view.removeFromSuperview()
        }
        cell.addSubview(childVC.view)
        return cell
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isForbidScrollDelegate = false
        starOffsetX = scrollView.contentOffset.x
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isForbidScrollDelegate {return}
        var progress:CGFloat = 0
        var sourceIndex = 0
        var targetIndex = 0
        
        let offsetX = scrollView.contentOffset.x
        let scrollWidth = scrollView.bounds.width
        let offsetIndex = offsetX / scrollWidth
        if offsetX > starOffsetX {   // 左滑
            progress = offsetIndex - floor(offsetIndex)
            sourceIndex = Int(offsetX/scrollWidth)
            targetIndex = sourceIndex + 1
            if targetIndex >= self.childVCs.count {
                targetIndex = self.childVCs.count - 1
            }
            if offsetX - starOffsetX == scrollWidth {
                progress = 1
                targetIndex = sourceIndex
            }
        }else{  // 右滑
            progress = 1 - (offsetIndex - floor(offsetIndex))
            targetIndex = Int(offsetX/scrollWidth)
            sourceIndex = targetIndex + 1
            if sourceIndex >= self.childVCs.count {
                sourceIndex = self.childVCs.count - 1
            }
            if progress == 1 {
                sourceIndex = targetIndex
            }
        }
//      print("targetIndex:\(targetIndex)----sourceIndex:\(sourceIndex)");
        delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
    }

}
// MARK:设置UI相关
extension PageContentView{
    private func setupSubviews() {
        addCollectionView()
    }
    private func addCollectionView() {
        addSubview(collectionView)
        for vc in childVCs{
            self.parentVC?.addChild(vc)
        }
    }
}
// MARK:对外暴露的方法
extension PageContentView{
    // 设置collectionView的偏移量
    func setScrollOffsetX(index:Int) {
        isForbidScrollDelegate = true
        collectionView.setContentOffset(CGPoint(x: CGFloat(index)*collectionView.bounds.size.width, y: 0), animated: false)
    }
}

